<template>
  <view class="cart-page">
    <view v-for="(shopItems, shopId) in groupedCartItems" :key="shopId">
      <!-- 显示商铺名字 -->
      <view v-if="shopItems.length > 0">
        <view class="shop-name">
          {{ shopItems[0].shopName }}
        </view>
        <!-- 全选复选框 -->
        <view class="select-all">
          <label>
            <checkbox :checked="isAllSelectedForShop(shopId)" @click="toggleSelectAllForShop(shopId)" color="#FF5722" />
            <text>全选</text>
          </label>
        </view>
        <view class="cart-item" v-for="(item, index) in shopItems" :key="item._id || index">
          <view class="item-left">
            <label>
              <checkbox :checked="item.selected" @click="toggleSelectForShop(shopId, index)" color="#FF5722" />
            </label>
          </view>
          <image :src="item.imgUrl" class="cart-item-img"></image>
          <view class="cart-item-info">
            <text class="cart-item-name">{{ item.name }} {{ item.specification }}</text>
            <br>
            <view class="quantity-container">
              <text>数量: </text>
              <button @click="decreaseQuantity(shopId, index)" :disabled="item.quantity <= 1" class="quantity-btn">-</button>
              <text>{{ item.quantity }}</text>
              <button @click="increaseQuantity(shopId, index)" class="quantity-btn">+</button>
            </view>
            <br>
            <text class="cart-item-price">单价: ¥{{ item.price }}</text>
          </view>
          <button class="delete-btn" @click="deleteCartItemForShop(shopId, index)">x</button>
        </view>
        <!-- 显示选中商品总价 -->
        <view class="selected-total">
          选中商品总价: <text class="price">¥{{ totalSelectedPriceForShop(shopId).toFixed(2) }}</text>
        </view>
        <!-- 添加每个商铺的结算按钮 -->
        <button class="checkout-btn-shop" @click="checkoutShopItems(shopId)">结算本商铺商品</button>
      </view>
    </view>
    <view v-if="Object.keys(groupedCartItems).length === 0" class="empty-cart">购物车为空</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      groupedCartItems: {} // 存储分组后的购物车商品
    };
  },
  computed: {
    // 这里可以根据需要添加计算属性，比如总的选中商品数量、总的选中商品价格等
  },
  onShow() {
    this.loadCartItems();
  },
  methods: {
    loadCartItems() {
      try {
        const cartItems = uni.getStorageSync('cartItems') || [];
        
        // 根据店铺 ID 进行分组
        const grouped = {};
        cartItems.forEach(item => {
          const shopId = item.shopId;
          if (!grouped[shopId]) {
            grouped[shopId] = [];
          }
          // 确保每个商品都有selected属性
          item.selected = item.selected !== false;
          grouped[shopId].push(item);
        });
        
        // 使用Object.assign触发响应式更新
        this.groupedCartItems = Object.assign({}, grouped);
      } catch (error) {
        console.error('读取本地存储购物车数据失败', error);
      }
    },
    saveCartItems() {
      try {
        const allCartItems = [];
        Object.values(this.groupedCartItems).forEach(items => {
          allCartItems.push(...items);
        });
        uni.setStorageSync('cartItems', allCartItems);
      } catch (error) {
        console.error('写入本地存储购物车数据失败', error);
      }
    },
    addProductToCart(shopId, shopName, product) {
      const existingItem = Object.values(this.groupedCartItems)
        .flat()
        .find(item => item._id === product._id);
      
      if (existingItem) {
        existingItem.quantity++;
        this.saveCartItems();
        return;
      }

      const newItem = {
        ...product,
        shopId,
        shopName,
        quantity: 1,
        specification: product.specification || "",
        selected: true
      };

      if (!this.groupedCartItems[shopId]) {
        this.$set(this.groupedCartItems, shopId, []);
      }
      
      this.groupedCartItems[shopId].push(newItem);
      this.saveCartItems();
    },
    deleteCartItemForShop(shopId, index) {
      this.groupedCartItems[shopId].splice(index, 1);
      if (this.groupedCartItems[shopId].length === 0) {
        this.$delete(this.groupedCartItems, shopId);
      }
      this.saveCartItems();
    },
    checkoutShopItems(shopId) {
      const shopItems = this.groupedCartItems[shopId];
      const selectedItems = shopItems.filter(item => item.selected);
      if (selectedItems.length === 0) {
        uni.showToast({
          title: '请选择要结算的商品',
          icon: 'none'
        });
        return;
      }
      try {
        const itemsString = JSON.stringify(selectedItems);
        uni.navigateTo({
          url: `/pages/detail/gotoCartpage?products=${itemsString}`
        });
      } catch (error) {
        console.error('数据传递失败', error);
        uni.showToast({
          title: '数据处理出错，请稍后重试',
          icon: 'none'
        });
      }
    },
    toggleSelectAllForShop(shopId) {
      const isAllSelected = this.isAllSelectedForShop(shopId);
      const shopItems = this.groupedCartItems[shopId];
      
      // 创建新数组确保响应式更新
      const updatedItems = shopItems.map(item => ({
        ...item,
        selected: !isAllSelected
      }));
      
      this.$set(this.groupedCartItems, shopId, updatedItems);
      this.saveCartItems();
    },
    toggleSelectForShop(shopId, index) {
      const shopItems = this.groupedCartItems[shopId];
      const updatedItems = [...shopItems];
      updatedItems[index] = {
        ...updatedItems[index],
        selected: !updatedItems[index].selected
      };
      
      this.$set(this.groupedCartItems, shopId, updatedItems);
      this.saveCartItems();
    },
    isAllSelectedForShop(shopId) {
      const shopItems = this.groupedCartItems[shopId];
      return shopItems && shopItems.length > 0 && shopItems.every(item => item.selected);
    },
    totalSelectedPriceForShop(shopId) {
      const shopItems = this.groupedCartItems[shopId];
      return shopItems.reduce((total, item) => {
        return item.selected ? total + item.price * item.quantity : total;
      }, 0);
    },
    increaseQuantity(shopId, index) {
      const shopItems = this.groupedCartItems[shopId];
      shopItems[index].quantity++;
      this.saveCartItems();
    },
    decreaseQuantity(shopId, index) {
      const shopItems = this.groupedCartItems[shopId];
      if (shopItems[index].quantity > 1) {
        shopItems[index].quantity--;
        this.saveCartItems();
      }
    }
  }
};
</script>

<style scoped>
.cart-page {
  padding: 20rpx;
  background-color: #f5f5f5;
}
.cart-item {
  display: flex;
  align-items: center;
  padding: 10rpx;
  background-color: white;
  border-bottom: 1px solid #eaeaea;
}
.item-left {
  margin-right: 10px;
}
.cart-item-img {
  width: 80rpx;
  height: 80rpx;
  margin-right: 10rpx;
}
.cart-item-info {
  flex: 1;
}
.cart-item-name {
  font-size: 28rpx;
  margin-bottom: 5rpx;
}
.quantity-container {
  display: flex;
  align-items: center;
}
.quantity-container text {
  margin: 0 2rpx;
}
.quantity-btn {
  background-color: #ccc;
  color: white;
  border: none;
  width: 25rpx;
  height: 25rpx;
  border-radius: 50%;
  font-size: 16rpx;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 1rpx;
}
.cart-item-price {
  font-size: 24rpx;
  color: #FF5722;
}
.empty-cart {
  text-align: center;
  padding: 50rpx;
  color: #999;
}
.delete-btn {
  background-color: #FF5722;
  color: white;
  border: none;
  width: 30rpx;
  height: 30rpx;
  border-radius: 50%;
  font-size: 18rpx;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
.select-all {
  padding: 10rpx;
  border-bottom: 1px solid #f5f5f5;
}
.selected-total {
  font-size: 14px;
  text-align: right;
  padding: 10rpx;
}
.price {
  color: #FF5722;
  font-size: 16px;
  font-weight: bold;
}
.shop-name {
  padding: 10rpx;
  font-size: 28rpx;
  font-weight: bold;
  border-bottom: 1px solid #eaeaea;
  background-color: #f5f5f5;
}
.checkout-btn-shop {
  height: 50px;
  width: 250px;
  background-color: #007AFF;
  color: white;
  border: none;
  padding: 10rpx 20rpx;
  border-radius: 5rpx;
  display: block;
  margin: 20rpx auto 0;
}
</style>